<template>
  <div class="CreaterContainer">
    <div class="Create-Box">
      <h1>创建团队</h1>
      <form @submit.prevent="createTeam">
        <div class="input-group">
          <label for="teamname">团队名称 <span class="required">*</span></label>
          <input
            type="text"
            id="teamname"
            v-model="inputteamname"
            placeholder="请输入团队名称"
            required
          />
          <span class="requirement">支持中英文、数字和下划线</span>
        </div>
        <div class="input-group">
          <label for="teamleader">团队负责人</label>
          <input
            type="text"
            id="teamleader"
            v-model="inputteamleader"
            placeholder="请输入团队负责人"
            required
            :disabled="true"
          />
        </div>
        <div class="input-group">
          <label for="description">团队描述</label>
          <textarea
            id="description"
            v-model="inputteamdescription"
            placeholder="简要描述团队职能或目标"
            required
            rows="3"
          ></textarea>
          <span class="requirement">不超过500个字，选填</span>
        </div>
        <div class="input-group">
          <label for="teamAvatar">团队头像</label>
          <input
            type="file"
            id="teamAvatar"
            accept="image/*"
            @change="handleFileChange"
          />
          <div v-if="selectedImage" class="image-preview">
            <img :src="selectedImage" alt="团队头像" class="preview-image" />
            <button type="button" @click="removeImage">移除图片</button>
          </div>
        </div>
        <div class="button-group">
          <button type="button"  class="back-btn" @click="BackHome">返回</button>
          <button type="submit" class="submit-btn">创建团队</button>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useTeamStore } from "../stores/teamStore.ts";
import { useUserStore } from "@/stores/userStore.ts";
import { useServer } from "../components/ts/useServer.ts";
import { useRouter } from "vue-router";
import default_teamimage from "@/assets/images/default_teamimage.png";

const router = useRouter();
const userStore = useUserStore();
const teamStore = useTeamStore();
const { postFile } = useServer();
const testUrl = 'https://m1.apifoxmock.com/m1/6951272-6668040-default/api'

// 表单输入相关
const inputteamname = ref("");
const inputteamleader = ref("");
const inputteamdescription = ref("一个普通的团队");
const UserId = ref("")
const selectedImage = ref(default_teamimage);
const fileToUpload = ref<File | null>(null);

onMounted(async () => {
  const currentUser = userStore.currentUserName;
  const currentUserId = userStore.currentUser;

  if (currentUser) {
    teamStore.currentUser = currentUser;
    inputteamleader.value = currentUser;
  }

  if(currentUserId) {
    UserId.value = currentUserId;
  }
});

// 处理文件上传
const handleFileChange = (e: Event) => {
  const input = e.target as HTMLInputElement;
  if (input.files && input.files[0]) {
    const file = input.files[0];

    if (file.size > 5 * 1024 * 1024) {
      alert("图片大小不能超过5MB");
      input.value = "";
      return;
    }

    const reader = new FileReader();
    reader.onload = (e) => {
      selectedImage.value = e.target?.result as string;
    };
    reader.readAsDataURL(file);
    fileToUpload.value = file;
  }
};

// 移除图片
const removeImage = () => {
  selectedImage.value = default_teamimage;
  fileToUpload.value = null;
  const input = document.getElementById("teamAvatar") as HTMLInputElement;
  if (input) input.value = "";
};

// 查重函数
const checkDuplicate = (newName: string, excludeTeamID?: string) => {
  return teamStore.teams.some((team) => {
    if (excludeTeamID && team.id === excludeTeamID) return false;
    return team.name.trim().toLowerCase() === newName.trim().toLowerCase();
  });
};

// 返回主页函数
const BackHome = () => {
  router.push("/team");
};

// 创建团队主函数
const createTeam = async () => {
  if (!inputteamname.value) {
    alert("请填写团队名称");
    return;
  }
  if (checkDuplicate(inputteamname.value)) {
    alert("团队名称已存在");
    return;
  }

  const formData = new FormData();
  formData.append("teamName", inputteamname.value);
  formData.append("teamLeader", UserId.value);
  formData.append("description", inputteamdescription.value);
  if (fileToUpload.value) {
    formData.append("teamAvatar", fileToUpload.value);
  }

  try {
    const res = await postFile("team/create", formData, testUrl);
    if (res.success) {
        teamStore.teams.push({
          id: res.teamId,
          thumbnail:
            fileToUpload.value? URL.createObjectURL(fileToUpload.value) : default_teamimage,
          name: inputteamname.value,
          description: inputteamdescription.value,
          admin: inputteamleader.value,
          openness: "need_audit",
          member_count: 1,
          access: res.teamAccess,
          projects: [],
        });
        inputteamname.value = "";
        inputteamdescription.value = "";
        selectedImage.value = default_teamimage;
        fileToUpload.value = null;
        const input = document.getElementById("teamAvatar") as HTMLInputElement;
        if (input) input.value = "";
        BackHome();
    }
  } catch (error) {
    console.error("创建团队失败", error);
    teamStore.error = "创建团队失败，请稍后再试";
  }
};
</script>

<style scoped>
/* 页面整体容器 */
.CreaterContainer {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background-color: #f5f7fa;
}

/* 创建团队卡片容器 */
.Create-Box {
  background-color: #fff;
  padding: 30px;
  border-radius: 12px; 
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05); 
  width: 100%;
  max-width: 500px;
}

/* 标题样式 */
.Create-Box h1 {
  font-size: 28px;
  color: #333; 
  margin-bottom: 20px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #e4e1e1;
}

.input-group {
  margin-bottom: 20px;
}

/* 标签样式 */
.input-group label {
  display: block;
  font-size: 14px;
  color: #666;
  margin-bottom: 6px;
  font-weight: 500;
}

/* 输入框通用样式 */
.input-group input,
.input-group textarea {
  width: 100%;
  padding: 10px;
  border-radius: 6px;
  border: 1px solid #e0e0e0;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s ease;
}

/* 输入框聚焦样式 */
.input-group input:focus,
.input-group textarea:focus {
  border-color: #4096ff;
}

/* 文本域样式 */
.input-group textarea {
  resize: none;
  height: 100px;
  overflow-y: auto;
}

.required {
  color: red;
}

.requirement {
  font-size: 12px;
  margin-left: 5px;
  color: #666;
}

/* 图片预览容器 */
.image-preview {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

/* 预览图片样式 */
.preview-image {
  max-width: 80px;
  max-height: 80px;
  border-radius: 4px;
  margin-right: 10px;
}

/* 移除图片按钮 */
.image-preview button {
  padding: 4px 8px;
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.image-preview button:hover {
  background-color: #e0e0e0;
}

/* 按钮组容器 */
.button-group {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 20px;
}

/* 返回按钮样式 */
.back-btn {
  padding: 10px 20px;
  background-color: #f0f0f0;
  color: #666;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
}

/* 创建按钮 */
.submit-btn {
  padding: 12px;
  background-color: #4096ff; /* 蓝色按钮 */
  color: #fff;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease, transform 0.2s ease;
  width: calc(60% - 100px); 
}

.back-btn:hover,
.submit-btn:hover {
  transform: translateY(-2px);
}
.back-btn:hover {
  background-color: #e0e0e0;
}
.submit-btn:hover {
  background-color: #2e85e6;
}
</style>